package com.open.pingban.fragment;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.open.pingban.MainActivity;
import com.open.pingban.R;
import com.open.pingban.adapter.MusicAdapter;
import com.open.pingban.mode.MusicData;
import com.open.pingban.utils.Config;
import com.open.pingban.utils.Constant;
import com.open.pingban.utils.OPENLOG;
import com.open.pingban.utils.Player;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * 音乐操作界面.
 */
public class AudioFragment extends BaseView {

    Player mMusicPlayer = Player.getPlayer();
    @InjectView(R.id.prve_btn)
    Button prveBtn;
    @InjectView(R.id.play_btn)
    Button playBtn;
    @InjectView(R.id.next_btn)
    Button nextBtn;
    @InjectView(R.id.progressBar)
    SeekBar progressBar;
    @InjectView(R.id.start_time_tv)
    TextView startTimeTv;
    @InjectView(R.id.end_time_tv)
    TextView endTimeTv;
    @InjectView(R.id.playlist_lv)
    ListView playlistLv;

    List<MusicData.AudiosBean> mMusicItems;
    MusicAdapter mMusicAdapter;

    public AudioFragment(Activity activity) {
        super(activity);
    }

    public static AudioFragment newInstance(Activity activity) {
        AudioFragment newFragment = new AudioFragment(activity);
        return newFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_audio, null, false);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated() {
        progressBar.setEnabled(false); // 禁止进度条可以拖动.
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mMusicPlayer.seekTo(seekBar.getProgress());
            }
        });
        mMusicAdapter = new MusicAdapter();
        mMusicPlayer.setOnMediaPlayerLister(new Player.OnMediaPlayerLister() {
            @Override
            public void onProgress(MediaPlayer mp, int value) {
                progressBar.setProgress(value); /* 更新进度条 */
                startTimeTv.setText("" + mMusicPlayer.sec2Time(value)); /* 更新进度时间 00:00:00 */
            }

            @Override
            public void onPrepared(MediaPlayer mp) {
                progressBar.setEnabled(true);
                progressBar.setMax(mp.getDuration());
                endTimeTv.setText("" + mMusicPlayer.sec2Time(mp.getDuration())); // 更新总时间

                mMusicPlayer.replay(); // 继续播放.
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
                setPlayOver();
            }

            @Override
            public void onPlayState(MediaPlayer mp, int state) {
                switch (state) {
                    case Config.PLAYING_PLAY:
                        playBtn.setBackgroundResource(R.drawable.play_btn_selector);
                        break;
                    case Config.PLAYING_PAUSE:
                        playBtn.setBackgroundResource(R.drawable.pause_btn_selector);
                        break;
                    case Config.PLAYING_STOP:
                        playBtn.setBackgroundResource(R.drawable.pause_btn_selector);
                        setPlayOver();
                        break;
                }
            }

        });
        playlistLv.setAdapter(mMusicAdapter);
        playlistLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ((MainActivity)getActivity()).stopAllVideoAndAudio(3);
                mMusicPlayer.play(getActivity(), mMusicItems, position);
            }
        });
        updateNetWorkView();
    }

    private void setPlayOver() {
        playBtn.setBackgroundResource(R.drawable.pause_btn_selector);
        progressBar.setEnabled(false);
        progressBar.setProgress(0);
        startTimeTv.setText("00:00:00");
        endTimeTv.setText("00:00:00");
    }

    @Override
    public void updateNetWorkView() {
        mUpdateHander.sendEmptyMessageDelayed(-250, 1600);
    }

    /**
     * 停止播放器.
     */
    @Override
    public void stopVideoView() {
        mMusicPlayer.stop();
    }

    Handler mUpdateHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                getAudioList();
            } catch (Exception e) {
                OPENLOG.E("" + e.getMessage());
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取音乐列表.
     */
    private void getAudioList() {
        OPENLOG.D(Constant.GET_AUDIO_LIST_URL);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        asyncHttpClient.get(Constant.ROOT_ADDR + Constant.GET_AUDIO_LIST_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    String data = new String(responseBody);
                    Gson gson = new Gson();
                    MusicData musicData = gson.fromJson(data, MusicData.class);
                    if (musicData != null) {
                        onSuccessFunction(musicData);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                onFailureFunction();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                onFailureFunction();
            }
        });
    }

    private void onFailureFunction() {
        showMsg("音乐列表获取失败");
    }

    private void onSuccessFunction(MusicData musicData) {
        List<MusicData.AudiosBean> musicItems = musicData.getAudios();
        mMusicItems = musicItems;
        mMusicAdapter.setMusicItems(mMusicItems);
        mMusicPlayer.setList(musicItems);
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        mMusicPlayer.destroy();
//    }

    @OnClick({R.id.prve_btn, R.id.play_btn, R.id.next_btn, R.id.rndom_btn, R.id.list_sequence_btn, R.id.single_repeat_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.prve_btn: // 上一曲
                try {
                    mMusicPlayer.previous(getActivity());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.play_btn: // 播放/暂停.
                if (mMusicPlayer.getPlaying() == Config.PLAYING_STOP) {
//                    mMusicPlayer.next  是否要播放(如果没有歌曲)
                    Log.d("hailongqiu", "onClick ==> play_btn ==> Config.PLAYING_STOP");
                } else {
                    if (mMusicPlayer.getPlaying() == Config.PLAYING_PLAY) {
                        mMusicPlayer.pause();
                    } else {
                        mMusicPlayer.replay(); // 继续播放.
                    }
                }
                break;
            case R.id.next_btn: // 下一曲
                try {
                    mMusicPlayer.next(getActivity());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.rndom_btn: // 随机播放
                try {
                    mMusicPlayer.setMode(Config.MODE_RANDOM);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.list_sequence_btn: // 列表循环.
                mMusicPlayer.setMode(Config.MODE_SEQUENCE);
                break;
            case R.id.single_repeat_btn: // 单曲循环.
                mMusicPlayer.setMode(Config.MODE_REPEAT_ALL);
                break;
        }
    }

}
